import React, { Component } from "react";
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import AgreeCheckbox from "@component/agreeCheckbox/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "@component/verCode/index";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList
} from "@redux/Action/bank/bank";
import { InterfaceG } from "@config/Config";
import BackModal from "@component/backModal/index";
import yhTools from "@tools/yh";
import PaypwdSet from "../paypwdVerify/PaypwdSet";
import { dropByCacheKey } from "react-router-cache-route";

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);
const phoneSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 3) +
			" " +
			value.substring(3, 7) +
			" " +
			value.substring(7, 11);
	}
	return tel;
};
const cardSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 4) +
			" " +
			value.substring(4, 8) +
			" " +
			value.substring(8, 12) +
			" " +
			value.substring(12, 16) +
			" " +
			value.substring(16, 19);
	}
	return tel;
};
const agreementPageMap = {
	huaTongAccount: "/huaTongBankElectronicAccountServiceAgreement",
	taxStatement: "/individualTaxResidentStatusStatement",
	pay: "/agreementoflianyintong"
};

const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();

/**
 * 专用于小辉宝开户的界面,开户之前需要设置支付密码
 */
@verCode()
@connect(
	state => ({
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		devicesInfo: state.getAppPlatformsDatas.devicesInfo
	}),
	dispatch => ({
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun))
	})
)
class AddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: "",
			isRead: false,
			messageSerialNumber: "",
			verifier: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			/** 设置密码弹出框显示 */
			setPaypwdVisible: false
		};
	}
	componentDidMount = () => {
		this.initbankInfo();
	};
	//初始化二要素
	initbankInfo() {
		let objs = {
			url: InterfaceG.initBankInfo,
			params: {},
			_alertShow: false
		};
		Toast.loading("加载中...", 20);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				if (res.data.bankCardNo) {
					this.setState({
						userBankPhone: phoneSeparated(res.data.bankCarPhone),
						accountNo: cardSeparated(res.data.bankCardNo)
					});
				}
				// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
				const { getSupportedBankList } = this.props;
				const { channelCode } = this.state;
				getSupportedBankList({ channelCode });
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	getMsgCode = () => {
		this.sendMsgCode();
	};
	sendMsgCode = () => {
		const { channelCode, accountNo, userBankPhone } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(60);
		const params = {
			channelCode,
			accountNo
		};
		let objs = {
			url: InterfaceG.openAccountSendCode,
			params: {
				...params,
				bankMobilePhone: submitCardRegexp(userBankPhone)
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 20);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { messageSerialNumber, verifier } = res.data;
				this.setState({
					messageSerialNumber,
					verifier,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	//小辉贷发送验证码
	xhdSendCode() {
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		const { userBankPhone, from } = this.state;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(userBankPhone)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(from === "bankList" ? 120 : 60); //连连和华通验证码时间不一样
		let objs = {
			url: InterfaceG.xhdSendCode,
			params: {
				mobilePhone: this.state.userBankPhone,
				lnid: this.props.lnid
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				this.setState({
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	openAccount = () => {
		const {
			accountNo,
			verifyCode,
			userBankPhone,
			messageSerialNumber
		} = this.state;
		console.log(accountNo, userBankPhone);
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.xhbOpenAccount,
				params: {
					cardNo: submitCardRegexp(accountNo),
					verifyCode,
					bankMobilePhone: submitCardRegexp(userBankPhone),
					messageSerialNumber,
					channelCode: "YHB",
					version: "1.0",
					deviceInfo: JSON.stringify(this.props.devicesInfo)
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(async res => {
				Toast.hide();
				this.setState({ canSubmit: true });

				if (res.code === "0") {
					dropByCacheKey("xhbAddBank");
					const cardNo = res.data.electronicCardNo;
					this.props.history.push(
						`/xhbOpenAccountResult?status=success&cardNo=${cardNo}`
					);
				} else if (
					// res.code === "60007" ||
					res.code === "00007" ||
					// res.code === "306003" ||
					// res.code === "00053" ||
					// res.code === "99999" ||
					// res.code === "99998" ||
					// res.code === "99000"
					res.code === "2"
				) {
					Toast.info(res.message);
				} else {
					this.setState({ verifyCode: "" });
					this.props.history.push(
						`/xhbOpenAccountResult?status=fail&errorMes=${res.message}`
					);
				}
			});
		}
	};
	InputOnChange = (key, value) => {
		this.setState({
			// [key]: submitCardRegexp(value)
			[key]: value
		});
	};
	toggleAgree = e => {
		if (e) {
			e.stopPropagation();
		}
		this.setState(prevState => {
			return { isRead: !prevState.isRead };
		});
	};

	checkCanSubmit = (cardNo, phoneNum, verifyCode) => {
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(cardNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}
		if (!this.state.isRead) {
			Toast.info("请先勾选协议");
			return false;
		}
		return true;
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.xhbgetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return res.data.status == "1";
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}

	saveBank = async () => {
		const { accountNo, verifyCode, userBankPhone } = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			let isSetPwd = await this.checkSetPassword();
			if (isSetPwd) {
				this.openAccount();
			} else {
				this.setState({ setPaypwdVisible: true });
			}
		}
	};
	/** 设置密码成功 */
	onSetPwdSuccess() {
		this.setState({ setPaypwdVisible: false }, () => {
			this.openAccount();
		});
	}

	//查看协议
	openContract = (e, type) => {
		e.stopPropagation();
		const { userName, idNo } = this.props.ocrInfo;
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isBackModalVisible: false
		});
		!booleanValue && this.setState({ verifyCode: "" });
		!booleanValue && this.props.history.push("/xhbBalanceNoAccount");
	};
	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};
	render() {
		const {
			isVisible,
			isBackModalVisible,
			userBankPhone,
			isRead,
			accountNo,
			hasSendCode
		} = this.state;
		const { supportedBankList, ocrInfo, lnid } = this.props;
		const _pageParams = {
			header: {
				title: "添加银行卡"
			},
			isModal: true,
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const { countDown, isClick } = this.props.verCode;
		const userName =
			ocrInfo.userName &&
			"*".repeat(ocrInfo.userName.length - 1) + ocrInfo.userName.slice(-1);
		return (
			<div>
				<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
					<BackModal
						product={lnid}
						isVisible={isBackModalVisible}
						onClick={this.onModalClick}
					/>
					<div className="add-bank-container">
						<InputItem
							className="my-input"
							defaultValue={userName}
							value={userName}
							disabled={true}
						>
							姓名
						</InputItem>
						{/* 23包括空格 */}
						<InputItem
							maxLength="23"
							className="my-input my-clear1"
							placeholder="请输入银行卡号"
							type="number"
							clear
							// defaultValue={accountNo}
							value={accountNo}
							onChange={this.InputOnChange.bind(this, "accountNo")}
						>
							银行卡号
							{/* <img
                                alt="guide"
                                className="icon-help"
                                src={BankIcon}
                                onClick={() => this.toggleVisible(true)}
                            /> */}
						</InputItem>
						<div className="bank-tips">
							<p>
								该卡可用于电子账户的充值和提现，
								<span onClick={() => this.toggleVisible(true)}>
									请查看支持银行
								</span>
							</p>
						</div>
						<InputItem
							clear
							type="phone"
							placeholder="请填写预留手机号"
							// defaultValue={userBankPhone}
							value={userBankPhone}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "userBankPhone")}
						>
							预留手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							pattern="[0-9]{6}"
							type="tel"
							value={this.state.verifyCode}
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.getMsgCode}>
								{/* {isClick ? "获取验证码" : countDown} */}

								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
						<div className="agree-wrapper">
							<AgreeCheckbox
								checked={isRead}
								onChange={e => this.toggleAgree(e)}
								multi={true}
							>
								<span className="multi-line">
									<a
										onClick={e => {
											this.toggleAgree(e);
										}}
									>
										本人同意并签署
									</a>
									<a
										className="font-link"
										onClick={e => this.openContract(e, "huaTongAccount")}
									>
										《福建华通银行电子账户服务协议》
									</a>
									<a
										className="font-link"
										onClick={e => this.openContract(e, "taxStatement")}
									>
										《个人税收居民身份声明》
									</a>
									<a
										onClick={e => {
											this.toggleAgree(e);
										}}
									>
										，并承诺本人是中国税收居民
									</a>
								</span>
							</AgreeCheckbox>
						</div>

						<Modal
							visible={isVisible}
							transparent
							maskClosable={true}
							title="支持银行及限额"
							closable={true}
							onClose={() => this.toggleVisible(false)}
							className="bank-list-modal"
						>
							<div style={{ height: 300, overflow: "scroll" }}>
								{supportedBankList.map(item => (
									<BankItem item={item} key={Math.random()} />
								))}
							</div>
						</Modal>

						<PaypwdSet
							visible={this.state.setPaypwdVisible}
							onSuccess={() => this.onSetPwdSuccess()}
							onClose={() => this.setState({ setPaypwdVisible: false })}
						/>

						<Button
							style={{ marginTop: "0.60rem" }}
							onClick={this.saveBank}
							// disabled={!isRead}
						>
							确认绑定
						</Button>
					</div>
				</MainLayout>
			</div>
		);
	}
}
export default AddBank;
